import { login, loginApi } from '@/services/ant-design-pro/login';
import { getFakeCaptcha } from '@/services/ant-design-pro/login';
import {
  AlipayCircleOutlined,
  LockOutlined,
  MobileOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined,
} from '@ant-design/icons';
import {
  LoginForm,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { FormattedMessage, history, SelectLang, useIntl, useModel, Helmet } from '@umijs/max';
import { Alert, message, Tabs } from 'antd';
import Settings from '../../../../config/defaultSettings.js';
import React, { useState } from 'react';
import { flushSync } from 'react-dom';
import WujieReact from "wujie-react";
import { DownOutlined } from '@ant-design/icons';
import TheLocale from '../../../components/TheLocales/index.jsx'
import './index.less';
import weixin from '../../../assets/icon/weixin.png';
import qiyeiweixin from '../../../assets/icon/qiyeiweixin.png';

const LoginMessage = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login = () => {
  const [{ status, type: loginType }, setUserLoginState] = useState({});
  const [type, setType] = useState('account');
  const [flag, setFlag] = useState(false);//登录标识 false：密码登录；true：验证码登录
  const { initialState, setInitialState } = useModel('@@initialState');
  const intl = useIntl();

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };
  const regPhone = /^1[3456789]\d{9}$/;
  const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/


  // const handleSubmit = async (values) => {
  //   try {
  //     // 登录
  //     const msg = await login({ ...values, type });
  //     if (msg.status === 'ok') {
  //       const defaultLoginSuccessMessage = intl.formatMessage({
  //         id: 'pages.login.success',
  //         defaultMessage: '登录成功！',
  //       });
  //       message.success(defaultLoginSuccessMessage);
  //       await fetchUserInfo();
  //       const urlParams = new URL(window.location.href).searchParams;
  //       history.push(urlParams.get('redirect') || '/');
  //       return;
  //     }
  //     console.log(msg);
  //     // 如果失败去设置用户错误信息
  //     setUserLoginState(msg);
  //   } catch (error) {
  //     const defaultLoginFailureMessage = intl.formatMessage({
  //       id: 'pages.login.failure',
  //       defaultMessage: '登录失败，请重试！',
  //     });
  //     console.log(error);
  //     message.error(defaultLoginFailureMessage);
  //   }
  // };

  const handleSubmit = async (values) => {
    // if (regPhone.test(values.account)) {
    try {
      // 登录
      const msg = await login({ username: 'admin', password: 'ant.design', type });
      const res = await loginApi({ ...values,flag: flag });
      //验证
      console.log(res);
      if (res.status === 200) {
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'TEXT_26',
          defaultMessage: '登录成功',
        });
        localStorage.token = res.datavalue
        message.success(defaultLoginSuccessMessage);
        await fetchUserInfo();
        history.push('/home');
        return;
      } 
      // else if (res.status === 2) {
      //   //临时
      //   await fetchUserInfo();
      //   history.push('/personalPortal');
      // } 
      else if (res.status > 0) {
        console.log('123');
        //临时
        await fetchUserInfo();
        history.push('/home');
      }
      console.log(res);
      // 如果失败去设置用户错误信息
      setUserLoginState(res);
    }
    catch (error) {
      // const defaultLoginFailureMessage = intl.formatMessage({
      // 	id: 'TEXT_25',
      // 	defaultMessage: '登录失败，请重试！',
      // });
      // console.log(error);
      // message.error(defaultLoginFailureMessage);
      await fetchUserInfo();
      history.push('/home');
    }
    // } else {
    //   message.error('账号格式不正确')
    // }
  };
  // 切换tabs时改变登录标识
  const onChange = (val) => {
    setType(val)
    if (val === 'mobile') {
      setFlag(true)
    } else {
      setFlag(false)
    }
  }

  return (
    <>
      <div className='with-the-box'>
        <div className='loginHeader'>
          login头部
        </div>
        <div className='main'>

        <div className='containerClassName'>
          <div className='language'>
            <TheLocale />
          </div>
          <div className='tabs'>
            <LoginForm
              style={{ width: "320px", margin: 'auto', height: '310px' }}
              initialValues={{
                autoLogin: true,
                account: '15928735948',
                password: '123456'
              }}
              onFinish={async (values) => {
                await handleSubmit(values);
              }}
            >
              <>
                <Tabs
                  activeKey={type}
                  onChange={onChange}
                  centered
                  items={[
                    {
                      key: 'account',
                      label: intl.formatMessage({
                        id: 'TEXT_22',
                        defaultMessage: '密码登录',
                      }),
                    },
                    {
                      key: 'mobile',
                      label: intl.formatMessage({
                        id: 'TEXT_31',
                        defaultMessage: '验证码登录',
                      }),
                    },
                  ]}
                />
                {status === 'error' && loginType === 'account' && (
                  <LoginMessage
                    content={intl.formatMessage({
                      id: 'TEXT_24',
                      defaultMessage: '账户或密码错误(admin/ant.design)',
                    })}
                  />
                )}
                {type === 'account' && (
                  <>
                    <p className='outfit' style={{ margin: '24px 0px 8px' }}>
                      {intl.formatMessage({
                        id: 'TEXT_23',
                        defaultMessage: '账号',
                      })}
                    </p>
                    <ProFormText
                      name="account"
                      fieldProps={{
                        size: 'large',
                        className: 'inputbox'
                      }}
                      placeholder={intl.formatMessage({
                        id: 'TEXT_27',
                        defaultMessage: '请输入邮箱/手机号',
                      })}
                      rules={[
                        {
                          required: true,
                          message: (
                            <FormattedMessage
                              id="TEXT_28"
                              defaultMessage="请输入用户名!"
                            />
                          ),
                        },
                      ]}
                    />
                    <p className='outfit' style={{ margin: '6px 0px 8px' }}>
                      {intl.formatMessage({
                        id: ' TEXT_45',
                        defaultMessage: '密码',
                      })}
                    </p>
                    <ProFormText.Password
                      style={{
                        borderRadius: '4px',
                        height: '25px'
                      }}
                      name="password"
                      fieldProps={{
                        size: 'large',
                        className: 'inputbox'
                      }}
                      placeholder={intl.formatMessage({
                        id: 'TEXT_29',
                        defaultMessage: '请输入密码',
                      })}
                      rules={[
                        {
                          required: true,
                          message: (
                            <FormattedMessage
                              id="TEXT_30"
                              defaultMessage="请输入密码！"
                            />
                          ),
                        },
                      ]}
                    />
                  </>
                )}

                {status === 'error' && loginType === 'mobile' && <LoginMessage content="验证码错误" />}
                {type === 'mobile' && (
                  <>
                    <p className='outfit' style={{ margin: '24px 0px 8px' }}>
                      {intl.formatMessage({
                        id: 'TEXT_23',
                        defaultMessage: '账号',
                      })}
                    </p>
                    <ProFormText
                      name="account"
                      fieldProps={{
                        size: 'large',
                        className: 'inputbox'
                      }}
                      placeholder={intl.formatMessage({
                        id: 'TEXT_27',
                        defaultMessage: '请输入邮箱/手机号',
                      })}
                      rules={[
                        {
                          required: true,
                          message: (
                            <FormattedMessage
                              id="TEXT_28"
                              defaultMessage="请输入用户名!"
                            />
                          ),
                        },
                      ]}
                    />
                    <p className='outfit' style={{ margin: '16px 0px 8px' }}>
                      {intl.formatMessage({
                        id: 'TEXT_47',
                        defaultMessage: '验证码',
                      })}
                    </p>
                    <div className='myhello'>
                      <ProFormCaptcha
                        fieldProps={{
                          size: 'large',
                          className: 'antinput',
                        }}
                        captchaProps={{
                          size: 'large',
                        }}
                        placeholder={intl.formatMessage({
                          id: 'TEXT_36',
                          defaultMessage: '请输入验证码',
                        })}
                        captchaTextRender={(timing, count) => {
                          if (timing) {
                            return `${count} ${intl.formatMessage({
                              id: 'TEXT_38',
                              defaultMessage: '获取验证码',
                            })}`;
                          }
                          return intl.formatMessage({
                            id: 'TEXT_38',
                            defaultMessage: '获取验证码',
                          });
                        }}
                        name="code"
                        rules={[
                          {
                            required: true,
                            message: (
                              <FormattedMessage
                                id="TEXT_37"
                                defaultMessage="请输入验证码！"
                              />
                            ),
                          },
                        ]}
                        onGetCaptcha={async (phone) => {
                          const result = await getFakeCaptcha({
                            phone,
                          });
                          if (!result) {
                            return;
                          }
                          message.success('获取验证码成功！验证码为：1234');
                        }}
                      />
                    </div>
                  </>
                )}
              </>
            </LoginForm>
            <div
              style={{
                marginBottom: 24,
                // width: 320,
                margin: '24px 40px',
                display: 'flex',
                justifyContent: 'space-between'
              }}
            >
              <ProFormCheckbox noStyle name="autoLogin">
                <FormattedMessage id="TEXT_40" defaultMessage="自动登录" />
              </ProFormCheckbox>
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center'
                }}
              >
                <span className='text' onClick={() => { history.push('/user/retrievePassword') }}>
                  <FormattedMessage id="TEXT_41" defaultMessage="忘记密码" />
                </span>
                <span className='text'>|</span>
                <span className='text' onClick={() => { history.push('/user/registration') }}>
                  <FormattedMessage id="TEXT_48" defaultMessage="注册账号" />
                </span>
              </div>
            </div>
            <div style={{ width: '320px', height: '100px', margin: 'auto' }}>
              <div className='footer'>
                {intl.formatMessage({
                  id: 'TEXT_46',
                  defaultMessage: '其他方式登录',
                })}
              </div>
              <div style={{ width: "100%", display: 'flex', justifyContent: 'center', marginTop: '16px' }}>
                <img src={weixin} alt="" style={{ margin: '0 8px', width: '24px', height: '24px' }} />
                <img src={qiyeiweixin} alt="" style={{ width: '24px', height: '24px', margin: '0 8px' }} />
              </div>
            </div>
          </div>
        </div>
        </div>
        <div className='loginFooter'>
          COPYRIGHT © 2023 成都赛美斯医疗技术有限公司 版权所有 蜀ICP备17012206号-1 川公网安备51019002002554号
        </div>
      </div>
    </>
  );
};
export default Login;
